<template>
  <van-uploader 
    :file-list="previewImgList" 
    @after-read="afterRead" 
    @delete="deletePicture"
    :max-count="maxCount"
    multiple 
    accept="image"
    preview-full-image 
  ></van-uploader>
</template>
<script>
import {
  model
} from "@/model";

const {
  Request
} = model;
export default {
  props: {
    maxCount: {
      type: Number,
      default: 9
    }
  },
  data () {
    return {
      request: new Request(),
      previewImgList: [],
      uploadedPictures: [],
    }
  },
  methods: {
    afterRead (e) {
      const {
        file
      } = e.detail;
      for (let item of file) {
        this.ossRequest(item);
      }
    },
    ossRequest (file) {
      this.request
        .do("open", "oss", "authorize", {
          params: {},
          data: {},
        })
        .then((res) => {
          if (res.status) {
            return this.upload(res.data, file);
          }
        })
        .then((res) => {
          if (res.status) {
            this.uploadedPictures.push({
              _file: file,
              info: {
                name: res.data.filename +'.'+ file.thumb.split('.')[1],
                size: file.size,
              },    
              oss: Object.assign({}, res.data),
            });
            file.deletable = true;
            file.type = "image";
            this.previewImgList.push(file);
            this.$emit('change', this.uploadedPictures);
          } else {
            throw new Error();
          }
        })
        .catch(() => {
          this.toast("上传图片失败");
        });
    },
    deletePicture (event) {
      this.previewImgList.splice(event.detail.index, 1);
      this.uploadedPictures.splice(event.detail.index, 1);
      this.$emit('change', this.uploadedPictures)
    }
  }
}
</script>